package com.ruoyi.project.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.ResponseResult;
import com.ruoyi.project.blog.domain.BCollect;
import com.ruoyi.project.blog.domain.vo.ApiArticleListVO;
import com.ruoyi.project.blog.mapper.BCollectMapper;
import com.ruoyi.project.blog.service.IBCollectService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class BCollectServiceImpl implements IBCollectService {

    private final BCollectMapper collectMapper;

    /**
     * 我的收藏列表
     *
     * @return
     */
    @Override
    public ResponseResult selectCollectList() {
        List<ApiArticleListVO> result = collectMapper.selectCollectList(SecurityUtils.getUserId().toString());
        return ResponseResult.success(result);
    }

    /**
     * 收藏文章
     *
     * @param articleId 文章id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult collect(Long articleId) {
        String principal = SecurityUtils.getAuthentication().getPrincipal().toString();
        Long userId = "anonymousUser".equals(principal) ? null : SecurityUtils.getUserId();
        BCollect collect = BCollect.builder().userId(userId).articleId(articleId).build();
        collectMapper.insert(collect);
        return ResponseResult.success();
    }

    /**
     * 取消收藏
     *
     * @param articleId 文章id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult cancel(Long articleId) {
        collectMapper.delete(new LambdaQueryWrapper<BCollect>().eq(BCollect::getUserId, SecurityUtils.getUserId().toString()).eq(BCollect::getArticleId, articleId));
        return ResponseResult.success();
    }
}
